use axum::{routing::{get, post}, Router};

use crate::{error::AppErr, server::{req::device::DeviceInfo, res::Void, Cbor}, store::cargo::{self, CargoExpiration, CargoInfo, CargoTimestamp, TbCargo}};

async fn on_get(info: DeviceInfo) -> Result<Cbor<Box<[TbCargo]>>, AppErr> {
    let cargos = cargo::get(info.id).await?;
    Ok(Cbor(cargos))
}

async fn on_change_product(info: DeviceInfo, cargos: Cbor<Box<[CargoInfo]>>) -> Result<Void, AppErr> {
    cargo::change_product(info.id, &cargos).await?;
    Ok(Void)
}

async fn on_change_timestamp(info: DeviceInfo, cargos: Cbor<Box<[CargoTimestamp]>>) -> Result<Void, AppErr> {
    cargo::change_update_timestmp(info.id, &cargos).await?;
    Ok(Void)
}

async fn on_query_expiration(info: DeviceInfo) -> Result<Cbor<Box<[CargoExpiration]>>, AppErr> {
    let ret = cargo::query_expiration(info.id).await?;
    Ok(Cbor(ret))
}

pub fn register() -> Router {
    Router::new()
    .route("/get", get(on_get))
    .route("/change_product", post(on_change_product))
    .route("/change_timestamp", post(on_change_timestamp))
    .route("/query_expiration", get(on_query_expiration))
}

